import { Router } from "@angular/router";
import {HttpService} from '../../../services/http.service';
import { BaseUiService } from '../../../services/base-ui.service';
import { LoginInfoService } from '../../../services/login-info.service';
import { commService } from '../../../services/comm.service'
import {EventService } from '../../../services/QaService';
import { WebsocketService } from '../../../services/websocket.service';
import {Component,OnInit,ChangeDetectorRef} from '@angular/core';
@Component({
  selector: "app-video",
  templateUrl: "./video.page.html",
  styleUrls: ["./video.page.scss"]
})
export class VideoPage{
  public notaryList:any;
  public info:any
  public notaryId = '';
  public relayCode="";
  public applyInfo = {
    userName:"",
    gender:'',
    birthday:'',
    idCard:'',
    mobile:'',
    
  };
  public userInfo= {
    userName:"",
    gender:'',
    birthday:'',
    idCard:'',
    mobile:'',
  };
  //   this.cd.detectChanges();
  constructor(
    public LoginInfoService: LoginInfoService,
    public router: Router, 
    public HttpService: HttpService,
    public baseUiService: BaseUiService,
    public commService:commService,
    public eventService:EventService,
    public wsCoket: WebsocketService,
    private cd: ChangeDetectorRef
    ) {
    this.getNotaryList();
  }

  ngOnInit() {
      
    Date.prototype["Format"] = function (fmt) { // author: meizz
      var o = {
          "M+": this.getMonth() + 1, // 月份
          "d+": this.getDate(), // 日
          "h+": this.getHours(), // 小时
          "m+": this.getMinutes(), // 分
          "s+": this.getSeconds(), // 秒
          "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
          "S": this.getMilliseconds() // 毫秒
      };
      if (/(y+)/.test(fmt))
          fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
      for (var k in o)
          if (new RegExp("(" + k + ")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
              return fmt;
    }


    this.eventService.eventEmitter.on('loginEvent',()=>{
      console.log("----------------login-------------",this.LoginInfoService.getInfo())//获取登录内容
      this.userInfo = this.LoginInfoService.getInfo();
      this.applyInfo=this.userInfo;
    })


    this.userInfo = this.LoginInfoService.getInfo();
    if(!this.userInfo){
      this.eventService.eventEmitter.emit('userInfo');    //通知用户中心更新用户信息
    }else{
      this.applyInfo=this.userInfo;
    }
  
  }

  getNotaryList(){
    this.HttpService.GET_notaryOffice({}).then(res=>{
      console.log(res, "11");
      if(res["code"]==200){
        this.notaryList = res["items"]
        this.notaryId = '666c2421-b2e1-4076-80aa-8e63cf287de4';
        this.cd.detectChanges()
      }
    })
  }


  getDate(){
          var myDate = new Date();
          //获取当前年
          var year = myDate.getFullYear();
          //获取当前月
          var month = myDate.getMonth() + 1;
          //获取当前日
          var date = myDate.getDate();
    //       var now = year + '-' + this.conver(month) + "-" + this.conver(date) + " " + this.conver(h) + ':' + this.conver(m) + ":" + this.conver(s);
          var now = year + '-' + this.conver(month) + "-" + this.conver(date)
          return now;
        }
    
        //日期时间处理
        conver(s) {
          return s < 10 ? '0' + s : s;
        }
  goFlow(){
    let that = this;
    if(this.notaryId==''){
      this.baseUiService.showToast('请选择公证处','danger','top')
    }else if(this.applyInfo.userName==""||this.applyInfo.birthday==""||this.applyInfo.idCard==""||this.applyInfo.mobile==""){
      this.baseUiService.showToast('请登录','danger','top')
      this.eventService.eventEmitter.emit('userInfo');    //通知用户中心更新用户信息
    }else{
      this.applyInfo.birthday = this.applyInfo.birthday.slice(0, 10)
      let p = {
            userId: this.LoginInfoService.getInfo().unitGuid,
            name:this.userInfo.userName,
            useArea:"",
            useLanguage:"",
            purposeName:"",
            notaryId:this.notaryId,
            isDaiBan:0,
            terminalType: 1,
            notaryForm:2,
            description:"",
            videolog:JSON.stringify({
              planDate:this.getDate()
            }),
            applyUsers:JSON.stringify([{
              name: this.LoginInfoService.getInfo().userName,
              gender: this.LoginInfoService.getInfo().gender,
              birthday: this.LoginInfoService.getInfo().birthday,
              idCard: this.LoginInfoService.getInfo().idCard, 
              mobile: this.LoginInfoService.getInfo().mobile,
              address: this.LoginInfoService.getInfo().registeAddress
            }]), 
          }
          this.HttpService.machineAdd(p).then(res => {
            console.log(res,'-+-+-')
            if(res['code'] == 200){
              let urlId = this.HttpService.websockurl() + this.userInfo.idCard
              this.wsCoket.createObservableScoket(urlId);
              if(res['unitGuid'].code == 11022){
                this.baseUiService.showLoading('正在等待公证员',0);
                //等待六十秒
                let timeOut = setTimeout(()=>{
                  that.HttpService.shutVideoOrder({unitGuid: res['unitGuid'].unitGuid})
                  that.baseUiService.hideLoading();
                  that.wsCoket.closeWebSocket();
                  that.baseUiService.showLoading('公证员正在忙碌，请稍后重试',1000);
                },60000)
                this.wsCoket.getMessage().subscribe(data => {
                  if(data.code == 'dontWiting'){
                    clearTimeout(timeOut)
                    that.baseUiService.hideLoading();
                    let info = {
                      orderNo: data.orderNo,
                      roomId: data.roomId
                    }
                    setTimeout(()=>{
                      that.LoginInfoService.setlocal('orderInfo', info)
                      that.router.navigate(['/transaction/startVideo']);
                    },1000)
                    
                  }
                })
              }else{
                this.LoginInfoService.setlocal('orderInfo', res['unitGuid'])
                this.router.navigate(['/transaction/startVideo']);
              }
            }
          })
    }
  }
    
}
